package com.framework.network.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.TimeUnit;

/**
 * @author duanzhizhou
 * @date 2025/6/10
 */
public class Client {
    
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline()
                            .addLast(new LineBasedFrameDecoder(1024))
                            .addLast(new StringEncoder())
                            .addLast(new StringDecoder())
                            .addLast(new SimpleChannelInboundHandler<String>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
                                    System.out.println(s);
                                }
                        });
                    }
                });
        ChannelFuture future = bootstrap.connect("localhost", 8080);
        future.addListener(f -> {
            if (f.isSuccess()) {
                System.out.println("客户端连接到8080端口");
                EventLoop eventLoop = future.channel().eventLoop();
                eventLoop.scheduleAtFixedRate(() -> future.channel().writeAndFlush("hello " + System.currentTimeMillis() + "\r\n") , 0, 1, TimeUnit.SECONDS);
            }
        });
    }
}
